package com.itheima.app.manager;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.itheima.app.exception.BusinessException;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.autoconfig.oss.OssTemplate;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.mongo.Comment;
import com.itheima.domain.mongo.FocusUser;
import com.itheima.domain.mongo.Video;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.mongo.CommentService;
import com.itheima.service.mongo.FocusUserService;
import com.itheima.service.mongo.VideoService;
import com.itheima.util.ConstantUtil;
import com.itheima.vo.CommentVo;
import com.itheima.vo.PageBeanVo;
import com.itheima.vo.VideoVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class VideoManager {



    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private FastFileStorageClient client;

    @Autowired
    private FdfsWebServer webServer;

    @Reference
    private CommentService commentService;

    @Reference
    private VideoService videoService;

    @Reference
    private UserInfoService userInfoService;

    @Reference
    private FocusUserService focusUserService;

    //查询推荐视频
    @Cacheable(value = "video", key = "#userId+'_'+#pageNum+'_'+#pageSize")
    public PageBeanVo findVideo(Long userId, Integer pageNum, Integer pageSize) {
        System.out.println("============================================");
        //1. 获取登录用户id
        //Long userId = UserHolder.get().getId();

        //2. 查询推荐给上面id的视频列表
        PageBeanVo pageBeanVo = videoService.findVideo(userId, pageNum, pageSize);

        //3. 处理返回结果
        List<Video> videoList = (List<Video>) pageBeanVo.getItems();
        List<VideoVo> videoVoList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(videoList)) {
            for (Video video : videoList) {
                //3-1 创建videoVo
                VideoVo videoVo = new VideoVo();

                //3-2 设置用户信息
                UserInfo userInfo = userInfoService.findByUserId(video.getUserId());
                BeanUtil.copyProperties(userInfo, videoVo);

                //3-3 设置视频信息
                BeanUtil.copyProperties(video, videoVo);
                videoVo.setCover(video.getPicUrl());//设置封面图片
                videoVo.setSignature(video.getText());//设置文案
                videoVo.setHasLiked(1);//todo  实战修改

                String key = StrUtil.format(ConstantUtil.FOCUS_USER, userId, video.getUserId());
                if (stringRedisTemplate.hasKey(key)) {
                    videoVo.setHasFocus(1);//已关注
                } else {
                    videoVo.setHasFocus(0);//未关注
                }

                //3-4  收集
                videoVoList.add(videoVo);
            }
        }

        pageBeanVo.setItems(videoVoList);
        return pageBeanVo;
    }

    //上传视频
    //@CacheEvict(value = "video", allEntries = true)
    @CacheEvict(value = "video", key = "#userId+'_*'")
    public void saveVideo(MultipartFile videoThumbnail, MultipartFile videoFile) throws IOException {
        //1. 封面上传阿里云
        String picUrl = ossTemplate.upload(videoThumbnail.getOriginalFilename(), videoThumbnail.getInputStream());

        //2. 视频上传fastsfs
        StorePath storePath = client.uploadFile(videoFile.getInputStream(),
                videoFile.getSize(), FileUtil.extName(videoFile.getOriginalFilename()), null);
        String videoUrl = webServer.getWebServerUrl() + storePath.getFullPath();


        //3. 组装一个video对象
        Video video = new Video();
        video.setCreated(System.currentTimeMillis());
        video.setUserId(UserHolder.get().getId());
        video.setText("女儿情");
        video.setPicUrl(picUrl);
        video.setVideoUrl(videoUrl);

        //获取用户id
        Long userId = UserHolder.get().getId();
       //从redis中拿到冻结动态标识码
        String freezeTime = stringRedisTemplate.opsForValue().get(ConstantUtil.Freeze_Time + userId);
        //从redis中拿到冻结范围标识码
        String freezeRange = stringRedisTemplate.opsForValue().get(ConstantUtil.Freeze_Range + userId);
        //判断redis中是否有标识
        if (StringUtils.isNotEmpty(freezeTime)&&StringUtils.equals(freezeRange,"3")) {
            throw new BusinessException("禁止该用户发布视频动态！");
        }else {
            //4. 调用service保存
            videoService.saveVideo(video);
        }


    }

    //添加关注
    public void saveUserFocus(Long focusUserId) {
        //1. 获取登录用户id
        Long userId = UserHolder.get().getId();

        //2. 组装FocusUser对象
        FocusUser focusUser = new FocusUser();
        focusUser.setUserId(userId);
        focusUser.setFocusUserId(focusUserId);
        focusUser.setCreated(System.currentTimeMillis());

        //3. 将关注标识保存到redis中
        String key = StrUtil.format(ConstantUtil.FOCUS_USER, userId, focusUserId);
        stringRedisTemplate.opsForValue().set(key, "1");

        //4. 调用service保存
        focusUserService.save(focusUser);
    }

    //删除关注
    public void deleteUserFocus(Long focusUserId) {
        //1. 获取登录用户id
        Long userId = UserHolder.get().getId();

        //2. 组装FocusUser对象
        FocusUser focusUser = new FocusUser();
        focusUser.setUserId(userId);
        focusUser.setFocusUserId(focusUserId);

        //3. 将关注标识从到redis中移除
        String key = StrUtil.format(ConstantUtil.FOCUS_USER, userId, focusUserId);
        stringRedisTemplate.delete(key);

        //4. 调用service保存
        focusUserService.delete(focusUser);
    }

    //视频点赞
    public void videoLike(String videoId) {
        //获取用户id
        Long userId = UserHolder.get().getId();

        //封装comment
        Comment comment = new Comment();
        comment.setUserId(userId);
        comment.setCommentType(4);
        comment.setPublishId(new ObjectId(videoId));


        //调用service
        commentService.saveVideoLikeComment(comment);
        //存储到redis中
        stringRedisTemplate.opsForValue().set(StrUtil.format(ConstantUtil.VIDEO_LIKE,userId,videoId),"1");

    }

    //取消视频点赞
    public void deleteVideoLike(String videoId) {
        //获取用户id
        Long userId = UserHolder.get().getId();
        //封装comment
        Comment comment = new Comment();
        comment.setUserId(userId);
        comment.setCommentType(4);
        comment.setPublishId(new ObjectId(videoId));
        //调用service删除点赞
        commentService.deleteVideoLike(comment);
        //从redis中删除点赞状态
        stringRedisTemplate.delete(StrUtil.format(ConstantUtil.VIDEO_LIKE,userId,videoId));

    }

    //视频评论
    public PageBeanVo findComments(String videoId, Integer pageNum, Integer pageSize) {
        //获取用户id
        Long userId = UserHolder.get().getId();
        //调用service查询pageBeanVo
        PageBeanVo pageBeanVo = commentService.findVideoComments(videoId,pageNum,pageSize);
        List<Comment> commentList = (List<Comment>) pageBeanVo.getItems();
        //创建集合
        List<CommentVo> commentVoList = new ArrayList<>();
        //判断集合commentList是否为空
        if (CollectionUtil.isNotEmpty(commentList)){
            //不为空遍历
            for (Comment comment : commentList) {
                //创建commentVo
                CommentVo commentVo = new CommentVo();
                UserInfo userInfo = userInfoService.findByUserId(comment.getUserId());
                BeanUtil.copyProperties(userInfo,commentVo);
                String key = StrUtil.format(ConstantUtil.VIDEO_COMMENT_LIKE, userId, comment.getId());
                if (stringRedisTemplate.hasKey(key)){
                    commentVo.setHasLiked(1);
                }
                commentVo.setLikeCount(comment.getLikeCount());
                commentVo.setContent(comment.getContent());
                commentVoList.add(commentVo);
            }
        }
        pageBeanVo.setItems(commentVoList);
        return pageBeanVo;
    }

    //视频评论保存
    public void saveVideoComment(String videoId, String content) {
        //获取用户id
        Long userId = UserHolder.get().getId();
        //组建comment
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(videoId));
        comment.setUserId(userId);
        comment.setCommentType(5);
        comment.setContent(content);
        //调用service
        commentService.saveVideoComment(comment);
    }
}
